package pro.spring.tool;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;

public class EmailSend {
	
	public Integer SendEmail(String Otheremail,String cpass){
		Integer num =0;
		HtmlEmail email = new HtmlEmail();
		email.setHostName("smtp.sina.com");
		try {
			//设置发件人
			email.setFrom("1231653468dsn@sina.com");
			//主题
			email.setSubject("微课学习平台,密码找回服务");
			//设置收件人
			email.addTo(Otheremail);
			//设置账号
			email.setAuthentication("1231653468dsn@sina.com", "dxstudio2005");
			// 设置邮件正文
			String content = "尊敬的用户，欢迎您使用微课学习平台密码找回服务，验证码为"+cpass+"。";
			email.setMsg(content);
			//设置编码
			email.setCharset("utf-8");
			email.send();
			num = 1;
		} catch (EmailException e) {
			e.printStackTrace();
		}
		return num ;
	}
	
	public Integer send(String othermeail,String cpass)  throws MessagingException{
		Integer num = 0;
		final Properties props = new Properties();
        // 表示SMTP发送邮件，需要进行身份验证
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", "smtp.sina.com");
        // 发件人的账号
        props.put("mail.user", "1231653468dsn@sina.com");
        // 访问SMTP服务时需要提供的密码
        props.put("mail.password", "dxstudio2005");
		String content = "尊敬的用户，欢迎您使用微课学习平台密码找回服务，验证码为"+cpass+"。";
        // 构建授权信息，用于进行SMTP进行身份验证
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // 用户名、密码
                String userName = props.getProperty("mail.user");
                String password = props.getProperty("mail.password");
                return new PasswordAuthentication(userName, password);
            }
        };
        // 使用环境属性和授权信息，创建邮件会话
        Session mailSession = Session.getInstance(props, authenticator);
        // 创建邮件消息
        MimeMessage message = new MimeMessage(mailSession);
        // 设置发件人
        InternetAddress form;
		form = new InternetAddress(props.getProperty("mail.user"));
        message.setFrom(form);
        // 设置收件人
        InternetAddress to = new InternetAddress(othermeail);
        message.setRecipient(RecipientType.TO, to);
        // 设置邮件标题
        message.setSubject("微课学习平台");
        // 设置邮件的内容体
        message.setContent(content, "text/html;charset=UTF-8");
        // 发送邮件
        Transport.send(message);
        num = 1;
		return num ;
	}
	
	
}
